/*
 * @Description:
 * @Version: 1.0
 * @Autor: chen_yt
 * @Date: 2022-05-30 16:29:11
 * @LastEditors: chen_yt
 * @LastEditTime: 2022-07-29 14:50:58
 */
import storage from '@/utils/storage'
import { getStoragePrefix } from '@/utils/storage'
import store from '@/store'
import { SET_REQUEST_TENANT_HEADER } from '@/store/Mutation/mutationTypes.js'
import { CLIENT_CONFIG } from '@/store/State/stateTypes.js'
import { IS_SAAS_MODE, MASTER_DATA_TYPE } from '@/store/Getter/getterTypes.js'
import { TOGGLE_CLIENT, LOADING_INIT_DATA } from '@/store/Action/actionTypes'
import { DATA_MODE_TYPE } from '@/config/enums'
import defaultSettings from '@/config'

const configInStorage = 'client_config'
/**
 * @description: saas化时增加租户id监听
 *               可以改成对clientInfo对象的监听
 */
export function addTenantListener() {
    if (addTenantListener.isCreated || !store.getters[IS_SAAS_MODE]) {
        return
    }
    window.addEventListener("storage", function (e) {
        if (e.key == `${getStoragePrefix()}${configInStorage}`) {
            let newClientConfig = storage.getObject(`${configInStorage}`)
            reloadClientConfig(newClientConfig)
        }
    })
    addTenantListener.isCreated = true
}


/**
 * @description: 查询该租户模式下是否可用
 * @param {Array}  tenantType  可选成员为'main', 'tenant','notSaas'
 * @param {String} dataName 需要鉴别的数据名称
 * @return {Boolean}  
 */
export function saasPermission(tenantType = [], dataName = '') {
    let currentTenantMode = [store.state[CLIENT_CONFIG].tenantMode]

    let result = tenantType.filter(item => currentTenantMode.includes(item));
    if (result.length > 0) {
        return true
    }

    return store.getters[MASTER_DATA_TYPE](dataName) == DATA_MODE_TYPE.TENANT
}



/**
 * @description: 切换租户后的操作
 *               重新加载应用配置
 *               配置项切换               
 *               
 * @param {String tenantId, String clientId} 租户id,应用id
 * @author: chen_yt
 */
export async function reloadClientConfig(clientConfig) {
    await store.dispatch(TOGGLE_CLIENT, clientConfig)
    //公钥
    //私钥
    //是否多门户
    //重新加载路由和权限，这里只要清空就行
    //清空并断开ws
    //重定向回home
}

export async function loadDefaultTenantConfig() {
    // if (!store.getters[IS_SAAS_MODE]) {
    //     return
    // }

    let currentClinetConfig = store.state[CLIENT_CONFIG]
    let { CLIENT: clientId, CLIENT_SECRET: clientSecret, TENANT: tenantId } = defaultSettings
    let clientConfig = { clientId, tenantId, clientSecret }


    //对象相等，已经加载了默认租户的配置
    if (JSON.stringify({ ...currentClinetConfig, ...clientConfig }) == JSON.stringify({ ...currentClinetConfig })) {
        return
    }

    store.commit(SET_REQUEST_TENANT_HEADER, clientConfig)
    await store.dispatch(LOADING_INIT_DATA)
}
